package homework.Matrices;

public class addMatrices {

    public static void main(String[] args) {
        // 创建两个3x3的矩阵
        int[][] matrix1 = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        int[][] matrix2 = {
                {9, 8, 7},
                {6, 5, 4},
                {3, 2, 1}
        };

        // 输出原始矩阵
        System.out.println("矩阵1:");
        printMatrix(matrix1);

        System.out.println("\n矩阵2:");
        printMatrix(matrix2);

        // 矩阵相加
        int[][] result = addMatrices(matrix1, matrix2);

        // 输出结果矩阵
        System.out.println("\n相加结果矩阵:");
        printMatrix(result);
    }


    public static int[][] addMatrices(int[][] m1, int[][] m2) {
        // 检查矩阵维度是否相同
        if (m1.length != m2.length || m1[0].length != m2[0].length) {
            throw new IllegalArgumentException("矩阵维度不匹配");
        }

        int rows = m1.length;
        int cols = m1[0].length;
        int[][] result = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[i][j] = m1[i][j] + m2[i][j];
            }
        }

        return result;
    }


    public static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int num : row) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
}
